package com.imisty.oa.global;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 通过拦截器进行登录限制以及访问控制
 */
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 如果是去登录的或者已经登陆的直接放行
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //获取请求的url判断是否有login关键字(登录相关路径)，才允许直接进行下一步操作
        String url = httpServletRequest.getRequestURI();
        if (url.toLowerCase().indexOf("login") >= 0){
            return true;
        }
        //判断是否登录,如果登录才进行下一步操作,否者直接重定向到登录界面
        HttpSession session = httpServletRequest.getSession();
        if (session.getAttribute("employee") != null){
            return true;
        }
        httpServletResponse.sendRedirect("/to_login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
